<script setup lang='ts' name="member-check-item">
import { ElCheckbox, ElCol, ElRow } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { toRefs } from 'vue'

const props = withDefaults(defineProps<{
    data?: any
}>(), {
    data: () => [],
})

const emits = defineEmits(['checkChange'])
const { data } = toRefs(props)

const list = ref<any>([])

watch(data, (val: any) => {
    if (val && val.length)
        init(val)
    else
        list.value = []
}, {
    deep: true,
    immediate: true,
})

function init(val: any) {
    const target: any = cloneDeep(val)
    if (target.length) {
        target.forEach((d: any) => {
            d.checked = '1' // 多选框
            d.selected = '' // 下拉框单选
            if (d.rules && d.rules.length) {
                d.selected = d.rules.find((v: any) => v.selected === '1' || v.selected === 1)?.ruleId || ''
                if (Object.keys(d.rules[0]).length === 1)
                    d.rules = []
            }
        })
    }
    list.value = target
}

function checkChange(val: any, key: number) {
    if (val === '0')
        list.value[key].selected = ''

    emits('checkChange', list.value[key], val === '1')
}

function getData() {
    const target: any = []
    list.value.length && list.value.forEach((v: any) => {
        const { checked, rightId, selected } = v
        if (checked === '1') {
            target.push({
                levelId: 0,
                rightId,
                ruleId: selected,
            })
        }
    })

    return target
}

defineExpose({
    getData,
})
</script>

<template>
    <div class="scroll_box">
        <ElRow v-for="(item, index) in list"
               :key="item?.id || item.rightId"
        >
            <ElCol :span="12">
                <ElCheckbox v-model="item.checked"
                            :label="item.rightName"
                            true-value="1"
                            false-value="0"
                            @change="checkChange($event, index)"
                />
            </ElCol>

            <ElCol v-if="item?.rules && item.rules.length"
                   :span="12"
            >
                <ElSelect v-model="item.selected"
                          placeholder="请选择"
                          clearable
                >
                    <ElOption v-for="rule in item.rules"
                              :key="rule.ruleId || rule.id"
                              :label="rule.ruleName || rule.name"
                              :value="rule.ruleId || rule.id"
                    />
                </ElSelect>
            </ElCol>
        </ElRow>
    </div>
</template>

<style lang="less" scoped>
.scroll_box {
    width: 350px;
    max-height: 250px;
    overflow-y: scroll;
    padding: 0 10px 0 0;
}
</style>
